package com.elf.zero.utils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.webkit.MimeTypeMap;

import androidx.core.content.FileProvider;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * 文件工具类
 * Created by Lidong on 2018/3/12.
 */
public class FileUtils {

    private static Context mContext;

    public static void init(Context context) {
        mContext = context;
    }

    /**
     * 获取文件目录
     *
     * @return 内部存储目录，优先获取sd卡文件目录，否则获取内部存储缓存目录
     */
    public static String getFileDir() {
        String path = "";
        if (Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED)) {
            File file = mContext.getExternalFilesDir(null);
            if (file != null) {
                path = file.getPath();
            }
        }

        if (TextUtils.isEmpty(path)) {
            path = mContext.getFilesDir().getPath();
        }
        return path;
    }


    /**
     * 获取缓存目录
     *
     * @return 缓存目录，优先获取sd卡缓存目录，否则获取内部存储缓存目录
     */
    public static String getCacheDir() {
        String path = "";
        if (Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED)) {
            File file = mContext.getExternalCacheDir();
            if (file != null) {
                path = file.getPath();
            }
        }

        if (TextUtils.isEmpty(path)) {
            path = mContext.getCacheDir().getPath();
        }
        return path;
    }


    public static void saveFile(String data, String fileName,boolean append) throws IOException {
        saveFile(data.getBytes(), fileName, append);
    }

    public static void saveFile(String data, File file,boolean append) throws IOException {
        saveFile(data.getBytes(), file, append);
    }

    public static void saveFile(byte[] data, String fileName,boolean append) throws IOException {
        saveFile(data, new File(fileName), append);
    }

    public static void saveFile(byte[] data, File file,boolean append) throws IOException {
        // 创建指定路径的文件
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        // 获取文件的输出流对象
        FileOutputStream outStream = new FileOutputStream(file, append);
        // 获取字符串对象的byte数组并写入文件流
        outStream.write(data);
        // 最后关闭文件输出流
        outStream.close();
    }

    /**
     * 保存文件
     *
     * @param bitmap   图片
     * @param fileName 文件地址
     */
    public static void saveFile(Bitmap bitmap, String fileName) throws IOException {
        // 创建指定路径的文件
        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        try {
            FileOutputStream saveImgOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, saveImgOut);
            saveImgOut.flush();
            saveImgOut.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void saveFile(String filename, InputStream in) {

        File file = new File(filename);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int ch = 0;
            while ((ch = in.read()) != -1) {
                os.write(ch);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public InputStream readFile(String filename) {
        File file = new File(filename);
        if (!file.exists()) {
            return null;
        }

        try {
            return new FileInputStream(file);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] readFile(File file) {
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        try {
            fis = new FileInputStream(file);
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int count = 0;
            while ((count = fis.read(buffer)) >= 0) {
                baos.write(buffer, 0, count);
            }
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取assets文件
     *
     * @param fileName 文件名称
     * @return 文件内容
     */
    public static String getAssetsFile(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(mContext.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = bufReader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 根据文件实际路径获取URI
     *
     * @param path 文件路径
     * @return URI
     */
    public static Uri pathToUri(String path) {
        if (path.startsWith("content:")) {
            return Uri.parse(path);
        }
        return pathToUri(new File(path));
    }

    /**
     * 根据文件取URI
     *
     * @param file 文件
     * @return URI
     */
    public static Uri pathToUri(File file) {
        String authority = mContext.getPackageName() + ".FileProvider";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //7.0及以上兼容
            return FileProvider.getUriForFile(mContext, authority, file);
        } else {
            return Uri.fromFile(file);
        }
    }

    /**
     * 根据URI找到文件实际路径
     *
     * @param uri uri
     * @return 文件实际路径
     */
    public static String uriToPath(Uri uri) {
        if (uri == null || TextUtils.isEmpty(uri.toString())) {
            return "";
        }

        String filePath = "";

        if (uri.toString().startsWith("file://")) {
            filePath = uri.toString().replaceFirst("file://", "");
            return filePath;
        } else if (uri.toString().startsWith("/")) {
            return uri.toString();
        }

        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            //picturePath就是图片在储存卡所在的位置
            filePath = cursor.getString(columnIndex);
        }
        if (cursor != null) {
            cursor.close();
        }
        return filePath;
    }

    /**
     * 获取指定mime的获取扩展名
     */
    public static String getExtensionFromMimeType(String mimeType) {
        return MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
    }
}
